//引入sql方法
const {
    exec
} = require('../db/mysql')

//查询所有用户的sql
const userList = () => {
    const sql = `select * from user`
    return exec(sql).then(rows => {
        return rows || {}
    })
}


//根据用户id查询用户
const selectById = (data) => {
    const sql = `select * from user where user_id=${data}`
    return exec(sql).then(rows => {
        return rows || {}
    })
}

//根据username查询用户
const selectByUsername = (data) => {
    const sql = `select * from user where username='${data}'`
    return exec(sql).then(rows => {
        return rows[0] || {}
    })
}

//增加用户
const addUser = (data) => {
    const sql = `insert into user(username,password,phone,address,role) values('${data.username}','${data.password}','${data.phone}','${data.address}','${data.role}')`
    return exec(sql).then(rows => {
        return rows || {}
    })
}

//删除用户
const deleteUser = (data) => {
    const sql = `delete from user where user_id=${data}`
    return exec(sql).then(rows => {
        return rows || {}
    })
}

//修改用户
const updateUser = (data) => {
    let sql = ''
    if (data.role) {
        sql = `update user set username='${data.username}',password='${data.password}',phone='${data.phone}',address='${data.address}',role='${data.role}' where user_id=${data.user_id}`
    }else {
        sql = `update user set username='${data.username}',password='${data.password}',phone='${data.phone}',address='${data.address}' where user_id=${data.user_id}`
    }
    return exec(sql).then(rows => {
        return rows || {}
    })
}

// 根据id修改地址
const updateAddressById = (data) => {
    const sql = `update user set address='${data.address}' where user_id=${data.user_id}`
    return exec(sql).then(rows => {
        return rows || {}
    })
}

//暴露
module.exports = {
    userList,
    addUser,
    selectById,
    deleteUser,
    updateUser,
    selectByUsername,
    updateAddressById
}
